package com.zl.tby.controller;

import com.zl.tby.core.base.util.EasyExcelUtils;
import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyMountainsPersonQuery;
import com.zl.tby.model.TbyMountainsPerson;
import com.zl.tby.service.ITbyMountainsPersonService;
import com.zl.tby.vo.TbyMountainsPersonForm;
import com.zl.tby.vo.exp.TbyMountainsPersonExportExcel;
import org.noear.solon.core.handle.Context;
import org.noear.solon.annotation.Body;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.validation.annotation.NotNull;
import org.noear.solon.validation.annotation.Valid;
import org.noear.solon.validation.annotation.Validated;

import java.io.IOException;
import java.util.List;

/**
 * 护林员信息控制器
 * @author changpeng
 * @version 1.0
 * @since 2024/8/6 20:22
 */
@Valid
@Controller
@Mapping("/mountains_person")
public class TbyMountainsPersonController {

    @Inject
    private ITbyMountainsPersonService tbyMountainsPersonService;

    /**
     * 保存或新增
     * @param entity: 表单对象
     * @return 操作结果
     */
    @Mapping(value = "/save", method = MethodType.POST)
    public R<TbyMountainsPerson> saveOrUpdate(@Validated TbyMountainsPerson entity) {
        try {
            return tbyMountainsPersonService.update(entity);
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.failed(ex.getMessage());
        }
    }

    /**
     * 根据id查询
     * @param id: 主键id
     * @return 结果
     */
    @Mapping(value = "/get", method = MethodType.GET)
    public R<TbyMountainsPersonForm> get(@NotNull Long id) {
        TbyMountainsPersonForm entity = this.tbyMountainsPersonService.get(id);
        return entity == null ? R.failed("数据不存在") : R.ok(entity);
    }

    /**
     * 分页查询
     * @param query: 查询参数
     * @return 分页结果
     */
    @Mapping(value = "/page", method = MethodType.GET)
    public R<?> page(@Body TbyMountainsPersonQuery query) {
        return R.ok(this.tbyMountainsPersonService.page(query));
    }

    /**
     * 导出Excel
     * @param query
     * @param ctx
     * @throws IOException
     */
    @Mapping(value = "/excel", method = MethodType.POST)
    public void excel(@Body TbyMountainsPersonQuery query, Context ctx) throws IOException {
        try {
            List<TbyMountainsPersonExportExcel> dataList = this.tbyMountainsPersonService.excel(query);
            EasyExcelUtils.exportExcel(ctx, dataList, TbyMountainsPersonExportExcel.class, "护林员", "护林员");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
